package cn.hdr.train.loadBalance;

import java.util.*;

/**
 * 随机负载均衡算法
 * @author: hdr
 * @date: 2020-08-14 13:51
 */
public class RandomLoadBalance {

    private final Random random = new Random();


    /**
     * 加权
     */
    public <T> T doWeightSelect(Map<T,Integer> map){
        Collection<Integer> values = map.values();
        int all = 0;
        for (Integer v:values) {
            all += v;
        }

        int r = random.nextInt(all);

        for (Map.Entry<T,Integer> entry:map.entrySet()) {
            r -= entry.getValue();

            if(r < 0){
                return entry.getKey();
            }
        }

        return null;
    }

    /**
     * 平权
     */
    public <T> T doSelect(List<T> list){
        int r = random.nextInt(list.size());
        return list.get(r);
    }


    public static void main(String[] args) {
        RandomLoadBalance loadBalance = new RandomLoadBalance();
        List<Integer> oList = Arrays.asList(0,1,2,3);
        int[] nums1 = new int[oList.size()];
        for (int i = 0; i < 10000; i++) {
            Integer v = loadBalance.doSelect(oList);
            nums1[v]++;
        }
        System.out.println(Arrays.toString(nums1));

        //----------加权-------
        Map<Integer,Integer> oMap = new HashMap<>();
        oMap.put(0,4);
        oMap.put(1,3);
        oMap.put(2,2);
        oMap.put(3,1);
        int[] nums2 = new int[oMap.size()];
        for (int i = 0; i < 100000; i++) {
            Integer v = loadBalance.doWeightSelect(oMap);
            nums2[v]++;
        }
        System.out.println(Arrays.toString(nums2));
    }
}